package cn.bonoon.controllers.schedule;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.bonoon.core.plugins.HolidayService;
import cn.bonoon.core.plugins.PersonalHolidayService;
import cn.bonoon.core.plugins.ScheduleService;
import cn.bonoon.entities.plugins.PersonalHolidayEntity;
import cn.bonoon.entities.plugins.ScheduleEntity;
import cn.bonoon.kernel.events.ReadEvent;
import cn.bonoon.kernel.support.models.Page;
import cn.bonoon.kernel.util.StringHelper;
import cn.bonoon.kernel.web.models.DialogModel;
import cn.bonoon.kernel.web.models.JsonResult;

/**
 * 个人行程安排（个人假期、日程安排、工作安排）
 * <pre>
 * 默认进入周视图
 * 年月周视图转换
 * 从日期上右键跳转的，则目标视图显示指定日期
 * 年 -> 月：年视图显示的年份是当前年份(yearview_year == current_year)？月视图显示当前月份：月视图显示1月；
 * 年 -> 周：年视图显示的年份是当前年份(yearview_year == current_year)？周视图显示当天的一周：周视图显示1月1日的周；
 * 月 -> 年：年视图显示月视图当前的年份；
 * 月 -> 周：月视图显示的年份是当前年份且月份是当前月份(monthview_year==current_year && monthview_month==current_month)？周视图显示当天的一周：周视图显示月视图1号的周；
 * 周 -> 年：显示周视图中隐藏框的年
 * 周 -> 月：显示周视图中隐藏框的年、月
 * </pre>
 * @author ocean~
 */
@Controller
@RequestMapping("s/user/schedule")
public class ScheduleController extends AbstractSchedule {

	@Autowired
	public ScheduleController(HolidayService holidayService, PersonalHolidayService personalHolidayService, ScheduleService scheduleService) {
		super(holidayService, personalHolidayService, scheduleService);
	}
	
	@RequestMapping(value = "personalHoliday/dialog", method = { POST, GET })
	public ModelAndView personalHoliday_dialog(HttpServletRequest request, Integer year, Integer month, Integer date) {
		DialogModel model = new DialogModel(request);
		String current_date = year + "-" + (month + 1) + "-" + date;
		model.addObject("attrs", "title='个人假日 | " + current_date + " " + format_week(week_of_day(year, month, date)) + "' style='width:700px;height:500px;'");
		model.addObject("id", current_date); // id of index_dialog
		return model.execute("user/schedule/personalHoliday-index-dlg");
	}
	
	@ResponseBody
	@RequestMapping(value = "personalHoliday/date/search", method = { RequestMethod.GET, RequestMethod.POST })
	public Page personalHoliday_search(HttpServletRequest request, @ModelAttribute("form") final PersonalHolidayCondition form) {
		try {
			ReadEvent event = new ReadEvent(applicationContext, request, getUser());
			return personalHolidayService.finder(form, event, PersonalHolidayItem.class).getPage();
		} catch (Exception e) {
			e.printStackTrace();
			return Page.EMPTY;
		}
	}
	
	@RequestMapping(value = "personalHoliday/date/editor", method = { POST, GET })
	public ModelAndView personalHoliday_editor(HttpServletRequest request, Long id) {
		DialogModel model = new DialogModel(request);
		if (null != id) { // update
			PersonalHolidayEntity entity = personalHolidayService.get(id);
			if (null != entity) {
				model.addObject("id", id);
				model.addObject("time", entity.getTime());
				model.addObject("type", entity.getType());
				model.addObject("duration", entity.getDuration());
				model.addObject("remark", entity.getRemark());
			}
		}
		return model.execute("user/schedule/personalHoliday-editor-dlg");
	}
	
	@RequestMapping(value = "personalHoliday/date/detail", method = { POST, GET })
	public ModelAndView personalHoliday_detail(HttpServletRequest request, Long id) {
		DialogModel model = new DialogModel(request);
		if (null != id) {
			PersonalHolidayEntity entity = personalHolidayService.get(id);
			if (null != entity) {
				model.addObject("id", id);
//				model.addObject("year", entity.getYear());
//				model.addObject("month", entity.getMonth());
//				model.addObject("date", entity.getDate());
				model.addObject("time", entity.getTime());
				model.addObject("type", entity.getType());
				model.addObject("duration", entity.getDuration());
				model.addObject("createAt", entity.getCreateAt());
				model.addObject("creatorName", entity.getCreatorName());
				model.addObject("remark", entity.getRemark());
			}
		}
		return model.execute("user/schedule/personalHoliday-detail-dlg");
	}
	
	@ResponseBody
	@RequestMapping(value = "personalHoliday/date/submit", method = { RequestMethod.GET, RequestMethod.POST })
	public JsonResult personalHoliday_submit(HttpServletRequest request, Long id, Integer year, Integer month, Integer date,
			Integer type, Integer time, Long duration, String remark) {
//		OperateEvent event = new OperateEvent(applicationContext, request, null, getUser());
//		event.setScope(VisibleScope.EXCLUSIVE);
		if (null != id) { // update
			PersonalHolidayEntity entity = personalHolidayService.get(id);
			if (null != entity) {
				entity.setType(type);
				entity.setTime(time);
				if (null != duration) {
					entity.setDuration(duration);
				}
				entity.setRemark(remark);
				personalHolidayService.update(entity);
			}
		} else { // insert
			PersonalHolidayEntity entity = new PersonalHolidayEntity();
			entity.setCreateAt(new Date());
			entity.setCreatorId(getUser().getId());
			entity.setCreatorName(getUsername());
			entity.setYear(year);
			entity.setMonth(month);
			entity.setDate(date);
			entity.setDates(year * PersonalHolidayService.Y + month * PersonalHolidayService.M + date);
			entity.setType(type);
			entity.setTime(time);
			if (null != duration) {
				entity.setDuration(duration);
			}
			entity.setRemark(remark);
			personalHolidayService.save(entity);
		}
		return JsonResult.result();
	}
	
	@ResponseBody
	@RequestMapping(value = "personalHoliday/date/delete", method = { RequestMethod.GET, RequestMethod.POST })
	public JsonResult personalHoliday_delete(HttpServletRequest request, String ids) {
		personalHolidayService.delete(getUser(), StringHelper.toLongArray(ids));
		return JsonResult.result();
	}
	
	@RequestMapping(value = "schedule/dialog", method = { POST, GET })
	public ModelAndView schedule_dialog(HttpServletRequest request, Integer year, Integer month, Integer date) {
		DialogModel model = new DialogModel(request);
		String current_date = year + "-" + (month + 1) + "-" + date;
		model.addObject("attrs", "title='行程安排 | " + current_date + " " + format_week(week_of_day(year, month, date)) + "' style='width:700px;height:500px;'");
		model.addObject("id", current_date);
		return model.execute("user/schedule/schedule-index-dlg");
	}
	
	@ResponseBody
	@RequestMapping(value = "schedule/date/search", method = { RequestMethod.GET, RequestMethod.POST })
	public Page schedule_search(HttpServletRequest request, @ModelAttribute("form") final ScheduleCondition form) {
		try {
			ReadEvent event = new ReadEvent(applicationContext, request, getUser());
			return scheduleService.finder(form, event, ScheduleItem.class).getPage();
		} catch (Exception e) {
			e.printStackTrace();
			return Page.EMPTY;
		}
	}
	
	@RequestMapping(value = "schedule/date/editor", method = { POST, GET })
	public ModelAndView schedule_editor(HttpServletRequest request, Long id) {
		DialogModel model = new DialogModel(request);
		if (null != id) { // update
			ScheduleEntity entity = scheduleService.get(id);
			if (null != entity) {
				model.addObject("id", id);
				model.addObject("name", entity.getName());
				model.addObject("type", entity.getType());
				model.addObject("content", entity.getContent());
				model.addObject("alarm", entity.isAlarm());
				model.addObject("alarmTime", entity.getAlarmTime());
				model.addObject("alarmType", entity.getAlarmType());
				model.addObject("remark", entity.getRemark());
			}
		}
		return model.execute("user/schedule/schedule-editor-dlg");
	}
	
	@RequestMapping(value = "schedule/date/detail", method = { POST, GET })
	public ModelAndView schedule_detail(HttpServletRequest request, Long id) {
		DialogModel model = new DialogModel(request);
		if (null != id) {
			ScheduleEntity entity = scheduleService.get(id);
			if (null != entity) {
				model.addObject("id", id);
				model.addObject("name", entity.getName());
				model.addObject("type", entity.getType());
				model.addObject("content", entity.getContent());
				model.addObject("alarm", entity.isAlarm());
				model.addObject("alarmTime", entity.getAlarmTime());
				model.addObject("alarmType", entity.getAlarmType());
				model.addObject("createAt", entity.getCreateAt());
				model.addObject("creatorName", entity.getCreatorName());
				model.addObject("updateAt", entity.getUpdateAt());
				model.addObject("updaterName", entity.getUpdaterName());
				model.addObject("remark", entity.getRemark());
			}
		}
		return model.execute("user/schedule/schedule-detail-dlg");
	}
	
	@ResponseBody
	@RequestMapping(value = "schedule/date/submit", method = { RequestMethod.GET, RequestMethod.POST })
	public JsonResult schedule_submit(HttpServletRequest request, Long id, Integer year, Integer month, Integer date, String name,
			Integer type, String content, Boolean alarm, Long alarmTime, Integer alarmType, String remark) {
//		OperateEvent event = new OperateEvent(applicationContext, request, null, getUser());
//		event.setScope(VisibleScope.EXCLUSIVE);
		if (null != id) { // update
			ScheduleEntity entity = scheduleService.get(id);
			if (null != entity) {
				entity.setUpdateAt(new Date());
				entity.setUpdaterId(getUser().getId());
				entity.setUpdaterName(getUsername());
				entity.setName(name);
				entity.setType(type);
				entity.setContent(content);
				entity.setAlarm(alarm);
				if (null != alarmTime) {
					entity.setAlarmTime(alarmTime);
				}
				entity.setAlarmType(alarmType);
				entity.setRemark(remark);
				scheduleService.update(entity);
			}
		} else { // insert
			ScheduleEntity entity = new ScheduleEntity();
			Calendar cal = Calendar.getInstance();
			cal.set(year, month, date);
			entity.setExecuteAt(cal.getTime());
			entity.setCreateAt(new Date());
			entity.setCreatorId(getUser().getId());
			entity.setCreatorName(getUsername());
			entity.setName(name);
			entity.setType(type);
			entity.setContent(content);
			entity.setAlarm(alarm);
			if (null != alarmTime) {
				entity.setAlarmTime(alarmTime);
			}
			entity.setAlarmType(alarmType);
			entity.setRemark(remark);
			scheduleService.save(entity);
		}
		return JsonResult.result();
	}
	
	@ResponseBody
	@RequestMapping(value = "schedule/date/delete", method = { RequestMethod.GET, RequestMethod.POST })
	public JsonResult schedule_delete(HttpServletRequest request, String ids) {
		scheduleService.delete(getUser(), StringHelper.toLongArray(ids));
		return JsonResult.result();
	}
	
}
